<template>
	<view>
		<view v-for="day in mealData" :key="day.dayNumber" class="day-block">
			<uni-section :title="day.label" type="line">
				<view v-for="meal in day.meals" :key="`${day.dayNumber}_${meal.type}`" class="meal-row">
					<view class="meal-label">{{ meal.type }}</view>
					<view v-if="['已领取'].includes(getStatus(meal))" class="meal-status">
						{{ getSelectedPackageName(meal) }} {{ getStatus(meal) }}
					</view>

					<uni-data-select v-else :value="selectedPackages[`${day.dayNumber}_${meal.type}`]"
						@change="(value) => handleSelectChange(value, day.dayNumber, meal.type,day.label)"
						:localdata="getOptions(meal)" :clear="true" placeholder="请选择套餐"></uni-data-select>
				</view>
			</uni-section>
		</view>
	</view>
</template>
<script>
	import {
		cancelOrder,
		getMealTableList,
		submitOrder
	} from '../../api/order/ordering';
	import constant from '../../utils/constant';
	import storage from '../../utils/storage';
	export default {
		data() {
			return {
				selectedPackages: {}, // { '20250422_午餐': 1, '20250422_晚餐': 3, ... }
				mealData: [], // 填入后端数据
				tempPackages: {},
			};
		},
		created() {
			this.fetchTableData();
		},

		methods: {
			async fetchTableData() {
				const data = {
					weekScope: '本周', //this.selectedWeek,
					userId: this.$store.getters.userId
				};

				try {
					const response = await getMealTableList(data);
					if (response.code === 200) {
						this.mealData = response.data || [];
						// 清空已有的 selectedPackages
						this.selectedPackages = {};

						// 更新 selectedPackages
						this.mealData.forEach(day => {
							day.meals.forEach(meal => {
								meal.packages.forEach(pkg => {
									if (pkg.status === '已领取' || pkg.status === '已报餐') {
										const key = `${pkg.dayNumber}_${pkg.type}`;
										this.selectedPackages[key] = pkg.id;
									}
								});
							});
						});
					} else {
						this.$message.error(response.msg || '获取数据失败');
					}
				} catch (error) {
					console.error('获取套餐数据出错', error);
					this.$message.error('请求失败');
				}
			},
			async handleSelectChange(newValue, dayNumber, mealType, weekDay) {
				const key = `${dayNumber}_${mealType}`;
				const oldValue = this.selectedPackages[key];

				// 不立即更新 selectedPackages，而是等处理完成后再更新
				const confirmed = await this.handleMealChange(dayNumber, mealType, oldValue, newValue, weekDay);
				if (confirmed) {
					this.fetchTableData()
				}
			},
			async handleMealChange(dayNumber, mealType, oldValue, newValue, weekDay) {
				const key = `${dayNumber}_${mealType}`;
				try {
					const day = this.mealData.find(d => d.dayNumber === dayNumber);
					if (!day) return false;
					const meal = day.meals.find(m => m.type === mealType);
					if (!meal) return false;

					const oldPackage = meal.packages.find(p => p.id === oldValue);
					const isExistingOrder = oldPackage && ['已报餐', '已领取'].includes(oldPackage.status);

					// 取消 or 切换
					if (isExistingOrder && newValue !== oldValue) {
						const actionType = newValue ? 'switch' : 'cancel';
						await this.showConfirmDialog(actionType, oldPackage, newValue, key, dayNumber,
							mealType, weekDay);
						return true;
					}
					// 新报餐
					else if (newValue && newValue !== oldValue) {
						await this.submitNewOrder(key, dayNumber, mealType, newValue, weekDay);
						return true;
					}
					return false;
				} catch (error) {
					console.error('处理订单变更失败:', error);
					uni.showToast({
						title: '操作失败，请重试',
						icon: 'none'
					});
					return false;
				}
			},
			showConfirmDialog(actionType, oldPackage, newValue, key, dayNumber, mealType, weekDay) {
				const confirmMap = {
					switch: {
						title: '切换套餐',
						content: `确定要将【${oldPackage.name}】切换为【${
				this.getPackageName(dayNumber, mealType, newValue)
			}】吗？`
					},
					cancel: {
						title: '取消报餐',
						content: '确定要取消当前报餐吗？'
					}
				};

				const {
					title,
					content
				} = confirmMap[actionType];

				return new Promise((resolve) => {
					uni.showModal({
						title,
						content,
						success: async (res) => {
							console.log('showModal 返回结果：', res);
							if (res.confirm) {
								uni.showLoading({
									title: '处理中...',
									mask: true
								});
								try {
									if (actionType === 'cancel') {
										await cancelOrder({
											packageId: oldPackage.id,
											dayNumber,
											mealType,
											userId: this.$store.getters.userId,
											weekDay: weekDay,
										});
									} else {
										await submitOrder({
											packageId: newValue,
											dayNumber,
											mealType,
											userId: this.$store.getters.userId,
											weekDay: weekDay,
										});
									}
								} finally {
									uni.hideLoading();
								}
								resolve(true);
							} else {
								this.fetchTableData()
								resolve(false);
							}
						}
					});
				});
			},
			async submitNewOrder(key, dayNumber, mealType, packageId, weekDay) {
				uni.showLoading({
					title: '提交中...',
					mask: true
				});
				try {
					await submitOrder({
						packageId,
						dayNumber,
						mealType,
						userId: this.$store.getters.userId,
						weekDay: weekDay,
					});
				} finally {
					uni.hideLoading();
				}
			},
			getPackageName(dayNumber, mealType, packageId) {
				const day = this.mealData.find(d => d.dayNumber === dayNumber);
				if (!day) return '';
				const meal = day.meals.find(m => m.type === mealType);
				return meal.packages.find(p => p.id === packageId)?.name || '';
			},
			// 其他保持原有方法不变
			getStatus(meal) {
				const pkg = meal.packages.find(p => ['已领取', '已报餐'].includes(p.status));
				return pkg ? pkg.status : '';
			},
			getSelectedPackageName(meal) {
				const pkg = meal.packages.find(p => ['已领取', '已报餐'].includes(p.status));
				return pkg ? pkg.name : '';
			},
			getOptions(meal) {
				return meal.packages.map(p => ({
					value: p.id,
					text: `${p.name}（${p.info}）`,
					disabled: p.status === '已领取'
				}));
			},
		}
	}
</script>

<style>
	.day-block {
		margin-bottom: 20rpx;
	}

	.meal-row {
		display: flex;
		align-items: center;
		margin: 10rpx 0;
	}

	.meal-label {
		width: 80rpx;
		font-weight: bold;
	}

	.meal-status {
		padding-left: 20rpx;
		color: #888;
	}
</style>